package com.enlorenz.common.security;

import com.enlorenz.common.security.des.Coder4DoubleDES;

/**
 * 主密钥下发工具
 * @author Karma
 */
public class ZMKDeliverUtils {
	private static Coder4DoubleDES coder4DoubleDES=new Coder4DoubleDES();
	private static final String CHECKVALUE_KEY="0000000000000000";
	/**
	 * 创建校验值
	 * @param value 传入值
	 * @return 校验值
	 */
	public static String createCheckValue(String value){
		String checkValue=coder4DoubleDES.encrypt(CHECKVALUE_KEY,value)
        .substring(0, 16);
		return checkValue;
	}
	/**
	 * 创建值
	 * @return
	 */
	public static String createKey(){
		return coder4DoubleDES.initKey();
	}

	/**
	 * 创建ZMK对象
	 * @return
	 */
	public static ZMKObject createZMKObject(){
		ZMKObject zmkObject=new ZMKObject();
		zmkObject.setKey1(createKey());
		zmkObject.setKey1CheckValue(createCheckValue(zmkObject.getKey1()));
		
		zmkObject.setKey2(createKey());
		zmkObject.setKey2CheckValue(createCheckValue(zmkObject.getKey2()));
		
		zmkObject.setZmk(composeZMK(zmkObject.getKey1(),zmkObject.getKey2()));
		zmkObject.setZmkCheckValue(createCheckValue(zmkObject.getZmk()));
		return zmkObject;
	}
	
	/**
	 * 合成主密钥
	 * @param key1 分量1
	 * @param key2 分量2
	 * @return 主密钥
	 */
	public static String composeZMK(String key1,String key2){
		return MacGenerate.xOr(key1,key2);
	}
	
	public static class ZMKObject{
		//分量1
		private String key1;
		//分量1校验值
		private String key1CheckValue;
		//分量2
		private String key2;
		//分量2校验值
		private String key2CheckValue;
		//主密钥
		private String zmk;
		//主密钥校验值
		private String zmkCheckValue;
		
		public String getKey1() {
			return key1;
		}
		public void setKey1(String key1) {
			this.key1 = key1;
		}
		public String getKey1CheckValue() {
			return key1CheckValue;
		}
		public void setKey1CheckValue(String key1CheckValue) {
			this.key1CheckValue = key1CheckValue;
		}
		public String getKey2() {
			return key2;
		}
		public void setKey2(String key2) {
			this.key2 = key2;
		}
		public String getKey2CheckValue() {
			return key2CheckValue;
		}
		public void setKey2CheckValue(String key2CheckValue) {
			this.key2CheckValue = key2CheckValue;
		}
		public String getZmk() {
			return zmk;
		}
		public void setZmk(String zmk) {
			this.zmk = zmk;
		}
		public String getZmkCheckValue() {
			return zmkCheckValue;
		}
		public void setZmkCheckValue(String zmkCheckValue) {
			this.zmkCheckValue = zmkCheckValue;
		}
	}
}
